import datetime
from applications.extensions import db

class Post(db.Model):
    __tablename__ = 'post'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='id')
    uid = db.Column(db.Integer, db.ForeignKey('user.uid'), nullable=False, comment='用户id')
    discuss_id = db.Column(db.Integer, default=0, comment='话题id')
    vote_id = db.Column(db.Integer, nullable=True, comment='投票id')
    title = db.Column(db.String(50), default='', comment='标题')
    content = db.Column(db.Text, comment='内容')
    media = db.Column(db.JSON, comment='文件')
    read_count = db.Column(db.Integer, default=0, comment='浏览量')
    type = db.Column(db.Integer, default=1, comment='帖子类型：1图文2视频3文章4投票')
    address = db.Column(db.String(255), nullable=True, comment='地址名称')
    longitude = db.Column(db.Numeric(10, 6), default=0.000000, comment='经度')
    latitude = db.Column(db.Numeric(10, 6), default=0.000000, comment='纬度')
    create_time = db.Column(db.DateTime, nullable=True, default=datetime.datetime.now, comment='创建时间')
    status = db.Column(db.Integer, default=0, nullable=False, comment='状态0正常1审核')
    pay = db.Column(db.Numeric(8, 2), default=0.00, nullable=False, comment='付费贴价格')
    brief = db.Column(db.String(255), default='', comment='付费简介')
    user = db.relationship('User', backref=db.backref('posts', lazy=True))

    def to_dict(self):
        """将帖子实例转换为字典"""
        return {
            'id': self.id,
            'uid': self.uid,
            'discussId': self.discuss_id,
            'voteId': self.vote_id,
            'title': self.title,
            'content': self.content,
            'media': self.media,
            'readCount': self.read_count,
            'type': self.type,
            'address': self.address,
            'longitude': str(self.longitude),  # 注意将 decimal 转换为字符串
            'latitude': str(self.latitude),    # 注意将 decimal 转换为字符串
            'createTime': self.create_time.isoformat() if self.create_time else None,
            'status': self.status,
            'pay': str(self.pay),              # 注意将 decimal 转换为字符串
            'brief': self.brief
        }
